﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sexybeauty.Framework.Common;
using Sexybeauty.Core.Inf.Entities;

namespace Sexybeauty.Core.Biz.HM.Impl
{
    internal class UserPopularity : IHitModify
    {
        public override void DoPersistence(string id)
        {
            using (Context ctx = new Context())
            {
                System.Threading.Monitor.Enter(LocalContext);
                var localData = LocalContext as UserPopularityContext;
                var userdetail = ctx.MemberDetail.FirstOrDefault(c => c.UserName == id);
                if (userdetail != null)
                {
                    userdetail.Fans += localData.Fans;
                    userdetail.Popularity += localData.Popularity;
                    userdetail.Wealth += localData.Wealth;
                    if (ctx.SaveChanges() > 0)
                    {
                        localData.Fans = 0;
                        localData.Popularity = 0;
                        localData.Wealth = 0;
                    }
                }
                else
                {
                    LogHelper.Write(CommonLogger.System, LogLevel.Info, "点击管理器处理持久化时，遇到空引用：" + localData.ToJson());
                }
                System.Threading.Monitor.Exit(LocalContext);
            }
        }

        public override void DoModify(object data)
        {
            try
            {
                System.Threading.Monitor.Enter(LocalContext);
                var localData = LocalContext as UserPopularityContext;
                UserPopularityContext realdata = data as UserPopularityContext;
                localData.Fans += realdata.Fans;
                localData.Popularity += realdata.Popularity;
                localData.Wealth += realdata.Wealth;
                LocalContext = localData;
                System.Threading.Monitor.Exit(LocalContext);
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
            }
        }
    }
    public class UserPopularityContext
    {
        /// <summary>
        /// 热门度
        /// </summary>
        public int Popularity { get; set; }
        /// <summary>
        /// 粉丝量
        /// </summary>
        public int Fans { get; set; }
        /// <summary>
        /// 财富值
        /// </summary>
        public int Wealth { get; set; }
    }
}
